package ldh.text.util;

import javafx.concurrent.Task;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.*;

public class ThreadPoolUtil {

    private static final Logger LOGGER = LoggerFactory.getLogger(ThreadPoolUtil.class);

    private static ExecutorService executorService = Executors.newFixedThreadPool(3);
    private static ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(2);

    public static void submit(Runnable runnable) {
        executorService.submit(runnable);
    }

    public static <T>Task<T> task(Callable<T> callable) {
        Task<T> task = new Task<T>() {

            @Override
            protected T call() throws Exception {
                return callable.call();
            }
        };
        executorService.submit(task);
        return task;
    }

    public static void schedule(Runnable runtime, long time) {
        scheduledExecutorService.schedule(runtime, time, TimeUnit.MICROSECONDS);
    }

    public static ScheduledFuture scheduleAtFixedRate(Runnable runtime, long time) {
        return scheduledExecutorService.scheduleAtFixedRate(runtime, 100, time, TimeUnit.MILLISECONDS);
    }

    public static void close() {
        executorService.shutdownNow();
        scheduledExecutorService.shutdownNow();
        LOGGER.info("close thread pool");
    }
}
